package com.soywer.rpc.rpc03;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

import com.soywer.rpc.common.IUserService;
import com.soywer.rpc.common.User;

/**
 * 功能描述：
 * 相对于rpc01,rpc02,这个版本改进最大，生成了一个动态代理类；但是客户端和服务端参数的传递，方法的调用等等都是写死的；
 * @author 18065916_李猛
 * @since 2021/3/8
 */
public class Stub {

    public static IUserService getStub(){
        InvocationHandler h = new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
                Socket s = new Socket("127.0.0.1",8888);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                DataOutputStream dos = new DataOutputStream(baos);
//                System.out.println(args.length);
//                System.out.println(args[0]);
                Integer writeId = (Integer)args[0];
                dos.writeInt(writeId);

                s.getOutputStream().write(baos.toByteArray());
                s.getOutputStream().flush();

                DataInputStream dis = new DataInputStream(s.getInputStream());
                int receiveId = dis.readInt();
                String name = dis.readUTF();
                User user = new User(receiveId , name);

                dos.close();
                s.close();
                return user;
            }
        };
        Object o = Proxy.newProxyInstance(IUserService.class.getClassLoader(),new Class[]{IUserService.class},h);
        System.out.println( "class name is " + o.getClass().getName());
        System.out.println(o.getClass().getInterfaces()[0]);
        return (IUserService)o;
    }

}
